<template>
    <el-tabs v-model="editableTabsValue"
    class="demo-tabs"
    @tab-remove="removeTab"
    tab-position="left" style="height: 90%">
    <el-tab-pane name="0" style="overflow: auto;">
      <template #label>
            <router-link :to="{path:'/cservice',query:{p :1}}">大厅
            </router-link>
      </template>
    <div class="demo-collapse" v-if="isWrite===false">

      <el-collapse v-model="activeName" accordion>
        
        <el-collapse-item v-for="item in items" :key="item.time" :name="item.sessionid">
        <template #title ><div class="ellipsis">{{ item.content }}</div><el-button :icon="selector(item.status)" :color="selector2(item.status)"></el-button></template>
        <template v-if="item.status==1">
              <div v-html="item.content"/>
          <p style="float:right; font-size: smaller; margin: 0;">序列号：{{ item.sessionid }}</p>
          <br>
          <p style="float:right; font-size: smaller; margin:0">发布日期：{{ item.time }}</p>
          <el-button type="primary" @click="takeup(item.sessionid)">接受</el-button>
          </template>
         </el-collapse-item>
     
        <el-collapse-item :key="pageSize" title="广告" :name="-1">
          <div>    
            placeholder
          </div>
          <p style="float:right; font-size: smaller;">发布日期：now</p>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" v-if="isAdmin==false" @click="isWrite=true">发布请求</el-button>
      <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 , 8 ,10, 15]"
                     layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                     @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    </div>

  <div class="stable" style="border: 1px solid #ccc" v-if="isWrite">
            <el-input
              v-model="textarea2"
              maxlength="100"
              show-word-limit
              placeholder="Input your question here or upload the image"
              :rows="3"
              type="textarea"        
            />
            <el-button-group style="float: right; margin-top: 5px">
              <el-button type="primary" :icon="PictureFilled" @click="uploadRef.$el.querySelector('input').click()"/>
              <el-button
                type="primary"
                :icon="Promotion" @click="addCService"
                >发送</el-button
                >
            <el-button type="danger" @click="isWrite=false">取消</el-button>
              
            </el-button-group>
            <el-upload
                ref="uploadRef"
                class="avatar-uploader"
                :show-file-list="false"
                action="/api/upload"
                name="file"
                :headers="{'Authorization': tokenStore.token}"
                :on-success="uploadSuccess"
            >
              <el-image v-if="imgUrl" :src="imgUrl" class="pic" :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :initial-index="4"
                fit="cover"
                style="width: auto; height: 100px"/>
            </el-upload>            
        </div>
    </el-tab-pane>
    <el-tab-pane v-for="one in editableTabs" :key="one.ind" :name="one.ind" style="overflow: auto;">
        <template #label>
            <router-link :to="{name: 'Chat', query: {sessionid : one.sessionid}}">
              {{ one.with }}
            </router-link>
        </template>
        <router-view v-slot="{Component}" ref="dontlisten" @senddata="whoyouarenow" :inf="one.ind" @senddata2="handleLeave">
          <transition>
            <div>
            <keep-alive>
              <component :is="Component"></component>
            </keep-alive></div>
          </transition>
        </router-view>
    </el-tab-pane>
    </el-tabs>
</template>
  
<script lang="ts" setup>
import { PictureRounded,Service, Star, Plus, Select,Promotion, PictureFilled,
  CirclePlus,Menu,Clock,CircleCheckFilled,CircleCheck,InfoFilled,QuestionFilled
}from '@element-plus/icons-vue'
import{useRouter} from 'vue-router';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { AnnouncementListService ,AddAnnouncementService} from '@/api/annocement';
import useUserInfoStore from '@/stores/userInfo.js';
const activeName = ref(0)
const userInfoStore = useUserInfoStore();
const isAdmin=(userInfoStore.userInfo.usertype===1);
const isWrite=ref(false);
import{useTokenStore} from "@/stores/token.js";
const  tokenStore = useTokenStore();
const imgUrl= ref('')
const textarea2 = ref('')
import request from '@/utils/request.js'
import {ElMessageBox,ElMessage} from "element-plus";
//import router from '@/router/index.js';
import { AddCServiceService, CServiceListService, UpdateCServiceService } from '@/api/cservice';
const uploadRef = ref()
const router = useRouter()

const addCService = async () =>{
  const newCServiceData=ref({
    content: textarea2.value,
    status: 1,
  })
  let result = await AddCServiceService(newCServiceData.value)
  ElMessage.success('发布成功')
  isWrite.value=false;
  const newTabName = `${++tabIndex}`
  console.log(result.data);
  editableTabs.value.push({
    sessionid: result.data,
    ind: newTabName,
    with: '?',
  })
  editableTabsValue.value = newTabName;
  router.push({name:'Chat',query:{sessionid: result.data}})
  
  textarea2.value=''
  //cs()
}
const removeTab = (targetName: string) => {
  const tabs = editableTabs.value
  /*
  let activeName1 = editableTabsValue.value
  if (activeName1 === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.ind === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName1 = nextTab.ind//改动
        }
      }
    })
  }

  */
  //router.push({path:'../'})
  //editableTabsValue.value = activeName1
  
  editableTabs.value = tabs.filter((tab) => tab.ind !== targetName)

  editableTabsValue.value = '0';
}
const selector = (sta : string)=>{
    switch(sta){
      case '0':
        return InfoFilled;
      case '1':
        return Clock;
      case '2':
        return CircleCheckFilled;
      default:
        return QuestionFilled;
    }
}

const selector2 = (sta : string) =>{
    switch(sta){
      case '0':
        return "909399";
      case '1':
        return "#409eff";
      case '2':
        return "#67c23a";
      default:
        return "ee82ee";
    }
}




const uploadSuccess=(result)=>{
    imgUrl.value=result.data;
}
const takeup= async (id) =>{
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
        sessionid: id,
        ind: newTabName,
        with: '?',
    })
    editableTabsValue.value = newTabName;
    router.push({name:'Chat',query:{sessionid: id}})
    //await UpdateCServiceService(id);
    //加入跳转

}
let tabIndex = 0
const editableTabsValue = ref('0')
const editableTabs = ref([])
const whoyouarenow = (name,inde)=>{
  console.log(name +'--'+inde)
  for(let i=0;i<editableTabs.value.length;i++){
    if(editableTabs.value[i].ind == inde){
      editableTabs.value[i].with = name;
    }
  }
  
  //window.removeEventListener("senddata",dontlisten.$el, true)
}
const handleLeave = (inde) =>{
  removeTab(inde)
}


const items = ref([{
    sessionid: '',
    status: '',
    content: '',
    time:''
},])

//const items = ref([])
//const message = ref('')

const pageNum = ref(+router.currentRoute.value.query.p)

const pageSize = ref(3)

const total = ref(0)
const onSizeChange = (size) => {
  pageSize.value = size
  cs();
}
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  pageNum.value = num
  
  await router.push({path:'',query:{p:num}})
  cs();
}



const show = ref(false)
const cs = async () =>{
  let params ={
      pageNum: router.currentRoute.value.query.p,
      pageSize:pageSize.value
    }
    let result = await CServiceListService(params)
    items.value = result.data.items
    total.value = result.data.total
}
cs()
const dontlisten =ref()

</script>

<style lang="scss" scoped>

.ellipsis{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

img:only-of-type{
    width: 500px;
    height: auto;
  }

.el-tabs--left .el-tabs__content {
  height: 500px;
  width: 100%;
}



.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #409eff;
  font-size: 32px;
  font-weight: 600;
}
.router-link-active {
  text-decoration: none;
  color: #409eff;

}
a{
  text-decoration: none;
  color: black;
}

</style>